package net.easyjava.base.manager;

import net.easyjava.base.bean.ArticleBean;
import net.easyjava.base.bean.cache.ArticleCacheBean;
import net.easyjava.base.bean.mongodb.ArticleDataBean;
import net.easyjava.base.constants.CommonConstants;
import net.easyjava.base.constants.ExceptionConstants;
import net.easyjava.base.service.ArticleService;
import net.easyjava.base.service.mongodb.ArticleDataService;
import net.easyjava.base.utils.qiniu.QiniuUploadUtils;
import net.easyjava.tools.http.HttpTools;
import net.easyjava.tools.http.ftp.FtpTools;
import net.easyjava.tools.http.request.RequestTools;
import net.easyjava.tools.id.IDTools;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.model.ModelConstants;
import net.easyjava.tools.page.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wenxiaoning on 15/12/18.
 */
@Service
public class ArticleManager extends BaseManager {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleDataService articleDataService;
//放弃ftp
//    @Value("${article_save_path}")
//    private String ARTICLE_SAVE_PATH;
//    @Value("${ftp.username}")
//    private String FTP_USERNAME;
//    @Value("${ftp.password}")
//    private String FTP_PASSWORD;
//    @Value("${ftp.ip}")
//    private String FTP_IP;


    /**
     * 保存文章
     * @param request
     * @param response
     * @return
     */
    public ModelBean save(HttpServletRequest request,HttpServletResponse response){
        try {
            String title = RequestTools.getParam(request, "title");
            String content = RequestTools.getParam(request,"content");
            String tags = RequestTools.getParam(request,"tags");
            String description = RequestTools.getParam(request,"description");
            int type = RequestTools.getParamInteger(request, "type","1");
            int isDisplay = RequestTools.getParamInteger(request, "isDisplay","1");
            int albumId = RequestTools.getParamInteger(request, "albumId","1");

            String userId = RequestTools.getParam(request,"userId",this.getUserId());

            ArticleBean articleBean = new ArticleBean();
            articleBean.setTitle(title);
            articleBean.setPath(content);
            articleBean.setTags(tags);
            articleBean.setDescription(description);
            articleBean.setType(type);
            articleBean.setIsDisplay(isDisplay);
            articleBean.setAlbumId(albumId);
            articleBean.setUserId(userId);
            return new ModelBean(articleService.save(articleBean));
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return new ModelBean(ModelConstants.STATUS_ERROR,ModelConstants.MESSAGE_ERROR);
        }
    }

    /**
     * 获取技术文章列表 web
     * @param pageNum
     * @return
     */
    public Page<ArticleCacheBean> getTechnologyArticleList(int pageNum){

        return articleService.findCacheAllList(pageNum, CommonConstants.PAGE_SIZE);
    }

    /**
     * 获取最新的文章列表 web
     * @return
     */
    public Page<ArticleCacheBean> getNeerArticleList(){
        return articleService.findCacheAllList(1, 4);
    }

    /**
     * 获取文章内容 web
     * @param url
     * @return
     * @throws IOException
     */
    public String getArticleContent(String url) throws IOException {
        return HttpTools.get(QiniuUploadUtils.getPrivateUrl(url));
    }


    /**
     * 添加或修改文章
     * @param articleBean
     * @return
     */
    public ModelBean edit(ArticleBean articleBean,String content){
        try {
            String id = articleBean.getId();

            //放弃ftp策略
//        FtpTools ftpTools = new FtpTools(FTP_USERNAME,FTP_PASSWORD,FTP_IP);
//            String dir = "file/article/"+StringTools.getRandomDir(4);//StringTools.getRandom(1)+FileTools.SEPARATOR+StringTools.getRandom(1)+FileTools.SEPARATOR+
//            String fileName = System.currentTimeMillis()+".txt";
//            String path = dir+fileName;
//            ftpTools.saveFile(dir, fileName, StringTools.escape(content).getBytes("UTF-8"));

            String path = QiniuUploadUtils.uploadArticle(content);
            articleBean.setPath(path);
            if("".equals(id)){
                articleBean = save(articleBean);
            }else{
                articleBean = update(articleBean);
            }
            return new ModelBean(articleBean);
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return new ModelBean(ModelConstants.STATUS_ERROR,ModelConstants.MESSAGE_ERROR);
        }
    }

    /**
     * 保存文章类
     * @param articleBean
     * @return
     */
    public ArticleBean save(ArticleBean articleBean) {
        articleBean.setId(IDTools.getObjectId());
        articleBean = articleService.save(articleBean);
        //保存文章数据
        ArticleDataBean articleDataBean = new ArticleDataBean();
        articleDataBean.setArticleId(articleBean.getId());
        articleDataService.save(articleDataBean);
        //保存缓存类
        ArticleCacheBean articleCacheBean = formatArticleCache(articleBean,articleDataBean);
        articleService.saveCache(articleCacheBean);
        return articleBean;
    }

    /**
     * 修改文章类
     * @param articleBean
     * @return
     */
    public ArticleBean update(ArticleBean articleBean){
        articleBean = articleService.update(articleBean);
        //修改文章数据
        ArticleDataBean articleDataBean = articleDataService.findByArticleId(articleBean.getId());
        articleDataBean.setUpdateCount(articleDataBean.getUpdateCount() + 1);
        articleDataService.update(articleDataBean);
        //修改缓存类
        ArticleCacheBean articleCacheBean = formatArticleCache(articleBean, articleDataBean);
        articleService.saveCache(articleCacheBean);
        return articleBean;
    }

    /**
     * 格式化文章缓存类
     * @param articleBean
     * @param articleDataBean
     * @return
     */
    public ArticleCacheBean formatArticleCache(ArticleBean articleBean,ArticleDataBean articleDataBean){
        ArticleCacheBean articleCacheBean = new ArticleCacheBean();
        try {
            articleCacheBean.setId(articleBean.getId());
            articleCacheBean.setTitle(articleBean.getTitle());
            articleCacheBean.setPath(articleBean.getPath());
            articleCacheBean.setType(articleBean.getType());
            articleCacheBean.setTags(articleBean.getTags());
            articleCacheBean.setDescription(articleBean.getDescription());
            articleCacheBean.setCreateTime(articleBean.getCreateTime());
            articleCacheBean.setUpdateTime(articleBean.getUpdateTime());
            articleCacheBean.setAlbumId(articleBean.getAlbumId());

            articleCacheBean.setViewCount(articleDataBean.getViewCount());
            articleCacheBean.setClickCount(articleDataBean.getClickCount());
            articleCacheBean.setCommentCount(articleDataBean.getCommentCount());
            articleCacheBean.setPraiseCount(articleDataBean.getPraiseCount());
            articleCacheBean.setLastViewTime(articleDataBean.getUpdateTime());


            return articleCacheBean;
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }


    /**
     * 查找一篇文章
     * @param request
     * @param response
     * @return
     */
    public ModelBean findOne(HttpServletRequest request,HttpServletResponse response){
        try {
            String id = RequestTools.getParam(request, "id");

            return new ModelBean(articleService.find(id));
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return new ModelBean(ModelConstants.STATUS_ERROR,ModelConstants.MESSAGE_ERROR);
        }
    }

    /**
     * 查找文章
     * @param id
     * @return
     */
    public ArticleBean findOne(String id){
        try {
            return articleService.find(id);
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }


    /**
     * 查找文章缓存类 web
     * @param id
     * @return
     */
    public ArticleCacheBean findCache(String id){
        try {
            return articleService.findCache(id);
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return null;
        }
    }

    /**
     * 查找文章列表
     * @param request
     * @param response
     * @return
     */
    public ModelBean findList(HttpServletRequest request,HttpServletResponse response){
        try {
            int albumId = RequestTools.getParamInteger(request, "albumId", "1");
            int pageNum = RequestTools.getParamInteger(request, "pageNum", "1");
            int pageSize = RequestTools.getParamInteger(request, "pageSize", "10");
            Map<String,Object> params = new HashMap<String, Object>();

            return new ModelBean(articleService.findList(params, pageNum, pageSize));
        }catch (Exception e){
            logger.error(e.getMessage(),e.fillInStackTrace());
            return new ModelBean(ModelConstants.STATUS_ERROR,ModelConstants.MESSAGE_ERROR);
        }
    }

    /**
     * 后台管理使用，查看文章列表
     * @param articleBean
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Page<ArticleBean> findList(ArticleBean articleBean,int pageNum,int pageSize){
        Map<String,Object> params = new HashMap<String,Object>();
        if(articleBean.getAlbumId() != 0 ){
            params.put("albumId",articleBean.getAlbumId());
        }
        if(articleBean.getTitle() != null && !"".equals(articleBean.getTitle())){
            params.put("title",articleBean.getTitle());
        }
        return articleService.findList(params, pageNum, pageSize);
    }

    /**
     * 获取最后一篇文章web站使用
     * @return
     */
    public ArticleBean findLastOne(){
        Map<String,Object> params = new HashMap<String,Object>();
        Page<ArticleBean> page = articleService.findList(params,1,1);

        return ((List<ArticleBean>)page.getRows()).get(0);
    }

    /**
     * 刷新缓存
     */
    public void resetCache(){
        articleService.removeCache();
        Page<ArticleBean> page = articleService.findAllList();
        List<ArticleBean> list = (List<ArticleBean>) page.getRows();
        for(ArticleBean articleBean:list){
            try {

                ArticleDataBean articleDataBean = articleDataService.find(articleBean.getId());
                ArticleCacheBean articleCacheBean = formatArticleCache(articleBean,articleDataBean);
                articleService.saveCache(articleCacheBean);
            }catch (Exception e){
                logger.error(ExceptionConstants.ARTICLE_RESET_CACHE,articleBean.getId());
                logger.error(e.getMessage(),e.fillInStackTrace());
            }
        }
    }



}
